package concurrency.chatper12;

import java.util.LinkedList;

/**
 * @author honway.liu
 * @date 2019/8/9 10:38 PM
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
public class MessageQueue {

    private final LinkedList<Message> messageQueue;

    private static final int defaultMaxQueueSize = 100;

    private int maxQueueSize = 100;

    public MessageQueue() {
        this(defaultMaxQueueSize);
    }

    public MessageQueue(int queueSize) {
        messageQueue = new LinkedList<>();
        this.maxQueueSize = queueSize;
    }


    public void put(Message msg) {
        synchronized (messageQueue) {
            while (messageQueue.size() >= maxQueueSize) {
                try {
                    messageQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            messageQueue.addLast(msg);
            messageQueue.notifyAll();
        }
    }

    public Message take() {
        synchronized (messageQueue) {
            while (messageQueue.size() == 0) {
                try {
                    messageQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message message = messageQueue.removeFirst();
            messageQueue.notifyAll();
            return message;
        }
    }

    public int queueSize() {
        synchronized (messageQueue) {
            return messageQueue.size();
        }
    }
}
